<?php

namespace app\api\services;

use app\api\constant\ConfigConst;

class BaseServices
{
    private static $instance;

    public static function getInstance()
    {
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }
    private function __construct()
    {
    }

    private function __clone()
    {

    }

    /**
     * 获取分页配置
     * @param bool $isPage
     * @param bool $isRelieve
     * @return int[]
     */
    public static function getPageValue(bool $isPage = true, bool $isRelieve = true): array
    {
        $page = $limit = 0;
        if ($isPage) {
            $page = input('page', 1);
            $limit = input('limit', 10);
        }
        return [(int)$page, (int)$limit,];
    }

    /**
     * 装饰完整的图片地址
     * @return void
     */
    public static function decorationImgPrefixUrl(array &$data, array $filePrefixes = [])
    {
        $baseUrl = ConfigConst::APP_URL;
        if (!empty($filePrefixes)) {
            foreach ($data as $k => &$v) {

                foreach ($filePrefixes as $prefix) {
                    if ($k == $prefix) {
                        $v = $baseUrl . $v;
                    }
                }
            }
            unset($v);
        }
    }

    /**
     * 通用分组函数
     * @param $collection
     * @param $key
     * @return array
     */
    public static function groupArrayByKey($collection, $key): array
    {
        $grouped = [];
        foreach ($collection as $item) {
            $groupName = $item[$key];
            if (!isset($grouped[$groupName])) {
                $grouped[$groupName] = [];
            }
            $grouped[$groupName][] = $item;
        }
        return $grouped;
    }

}